package page;

import com.fasterxml.jackson.core.type.TypeReference;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.dataformat.yaml.YAMLFactory;
import org.junit.Assert;
import org.openqa.selenium.By;
import org.openqa.selenium.Cookie;
import org.openqa.selenium.WebDriver;

import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Set;

public class WeWork extends BasePage {

    public static final String WEWORK_LOGIN_URL = "https://work.weixin.qq.com/wework_admin/frame";

    /**
     * 构造函数
     *
     * @param driver WebDriver
     */
    public WeWork(WebDriver driver) {
        super(driver);
        System.out.println("ContactPage driver：" + driver.toString());
    }

    /**
     * 启动浏览器并打开企业微信登录页面
     *
     * @return 返回当前页面的PO
     */
    public WeWork startWeb() {
        driver.get(WEWORK_LOGIN_URL);
        return this;
    }

    /**
     * 扫码登录企业微信
     *
     * @return 返回首页PO
     */
    public MainPage login() {
        try {
//            driver.get(WEWORK_LOGIN_URL);
            //等待10秒扫码
            Thread.sleep(10000);
            driver.navigate().refresh();
            if (isVisiable(By.linkText("退出"), 3)) {
                try {
                    saveCookies();
                } catch (IOException e) {
                    e.printStackTrace();
                    System.out.println("保存Cookies失败");
                }
                return new MainPage(driver);
            } else {
                System.out.println("请及时扫码登录");
                return null;
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
            return null;
        }
    }

    /**
     * Cookies登录企业微信
     *
     * @return 返回首页PO
     */
    public MainPage loginFromCookies() {
        try {

            //TODO：逻辑待优化，就在当前页面重新扫码登录后保存有点问题
            //打开网页->读取YAML文件并设置Cookies->完成登录

            driver.get(WEWORK_LOGIN_URL);

            ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());
            TypeReference<List<HashMap<String, Object>>> typeReference = new TypeReference<List<HashMap<String, Object>>>() {
            };

            File handleOfCookiesFile = new File(new File(new Object() {
                public String getPath() {
                    return this.getClass().getResource("/").getPath() + "data";
                }
            }.getPath()), "cookies.yaml");

            if (!handleOfCookiesFile.exists()) {
                Assert.fail("Cookies文件不存在，请在运行链路中添加loginAndSaveCookies");
            }

            List<HashMap<String, Object>> cookies = objectMapper.readValue(handleOfCookiesFile, typeReference);
            cookies.forEach(cookie -> driver.manage().addCookie(new Cookie(cookie.get("name").toString(), cookie.get("value").toString())));

            driver.navigate().refresh();
            if (isVisiable(By.linkText("通讯录"), 5)) {
                return new MainPage(driver);
            } else {
                System.out.println("Cookie登录失败，请检查");
                return null;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    private void saveCookies() throws IOException {
        //读取Cookies并存入文件
        Set<Cookie> cookies = driver.manage().getCookies();
        ObjectMapper objectMapper = new ObjectMapper(new YAMLFactory());

        //创建YAML文件的父目录(不管有无)
        String parentDir = new Object() {
            public String getPath() {
                return this.getClass().getResource("/").getPath() + "data";
            }
        }.getPath();

        System.out.println("目录为："+parentDir);
        File dir = new File(parentDir);
        dir.mkdir();

        File handleOfCookiesFile = new File(parentDir, "cookies.yaml");

        if (!handleOfCookiesFile.exists()) {
            handleOfCookiesFile.createNewFile();
        }
        objectMapper.writeValue(handleOfCookiesFile, cookies);
        System.out.println("写文件成功");
    }

    /**
     * 退出登录
     *
     * @return 退出登录的结果
     */
    public boolean logout() {
        //TODO：待完善
        driver.findElement(By.id("logout")).click();
        return true;
    }
}
